<template>
  <view class="page page-primary page-product-list">
    <page-header theme="colorful"></page-header>
    <view class="page-content">
      <page-statistic :data="userType === '2' ? statisticData2 : statisticData1"></page-statistic>
      <view class="page-search">
        <fui-input v-model="searchValue" borderTop color="#333" radius=16 :borderBottom="false" placeholderStyle="font-size:28rpx" placeholder="请输入商品名称"></fui-input>
        <span class="icon iconfont" @click="searchCenter">&#xe628;</span>
      </view>
      <view class="page-parent-tab" v-if="userType === '1'">
        <fui-tabs :tabs="parentTabs" @change="onChangeParentTab" background="transparent" size="32" color="#666" sliderRadius="-1" 
        :center="true" fontWeight="bold" selectedSize="32" selectedColor="#376DFE" scale="1" sliderHeight="8" selectedFontWeight="bold" bottom="3"></fui-tabs>
      </view>
      <view class="page-child-tab">
        <fui-tabs :tabs="showChildTabs" @change="onChangeChildTab" background="transparent" scale="1" sliderHeight="0"></fui-tabs>
      </view>
      <view class="product-list">
        <view class="product-item" v-for="item in listData" :key="item.id" @click="handleToView(item.id)">
          <image :src="item.sliderPicUrls[0]" style="width: 164rpx; height: 164rpx; border-radius: 16rpx; overflow: hidden;" mode=""></image>
          <view class="product-item-right">
            <view class="right-title">{{item.name}}</view>
            <view class="right-list">
              <view class="right-text" v-if="curParentTab">
                <image src="/static/images/icon-gys.png" style="width: 24rpx; height: 22rpx;"></image>
                {{item.deptName}}
              </view>
              <view class="right-text">
                <image src="/static/images/icon-kc.png" style="width: 22rpx; height: 22rpx;"></image>
                库存 <span class="right-number">{{item.stock}}</span><span>{{item.unit}}</span>
              </view>
              <view class="right-text">
                <image src="/static/images/iocn-dj.png" style="width: 26rpx; height: 26rpx;"></image>
                单价 <span class="right-number">{{ utils.moneyFormatter(item.qgjg / 100)}}</span><span>元/{{item.unit}}</span>
              </view>
              <view class="right-text">
                <image src="/static/images/icon-qssl.png" style="width: 24rpx; height: 22rpx;"></image>
                起售数量 <span class="right-number">{{item.qgsl}}</span><span>{{item.unit}}</span>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <fui-fab v-if="isSelf" background="#376DFE" position="right" :fabs="floatBtns" @click="onClickBtn"></fui-fab>
    <fui-loadmore v-show="listData.length" :state="moreState"></fui-loadmore>
    <fui-empty v-show="!listData.length" src="/static/images/empty/data.png" marginTop="240" title="暂无商品信息" size="28" color="#999"></fui-empty>
  </view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { useStore	} from 'vuex'
import { formatValue, formatUnit } from '@/utils/tools'
import utils from '@/components/firstui/fui-utils'
import pageHeader from '@/components/header'
import pageStatistic from '@/components/statistic'
import productApi from '@/api/product'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const userType = computed(() => store.getters.userType)
const isSelf = computed(() => curParentTab.value === 0)
const { currentTenantId, currentDeptId, companyId } = store.getters

// 搜索
const searchValue = ref('')
const searchCenter = (e) => {
  queryParams.value.pageNo = 1
  getProductList()
}

// 一级标签页
const parentTabs = ref(['自营商品', '直供商品'])
const curParentTab = ref(0)
const onChangeParentTab = (e) => {
  curParentTab.value = e.index
  queryParams.value.pageNo = 1
  getProductList()
}

// 二级标签页
const childTabs = ref([
  { name: '已上架', parent: '0,1', value: '0' },
  { name: '审核中', parent: '1', value: '5' },
  { name: '已驳回', parent: '1', value: '8' },
  { name: '已下架', parent: '0,1', value: '1' },
  { name: '商品目录', parent: '0', value: '6' }
])
const showChildTabs = computed(() => childTabs.value.filter(item => userType.value === '2' || item.parent.indexOf(curParentTab.value) > -1))
const curChildTab = ref('0')
const onChangeChildTab = (e) => {
  curChildTab.value = e.value
  queryParams.value.pageNo = 1
  getProductList()
}

// 浮动按钮组
const floatBtns = [
  { name: 'goods', text: '新增商品', link: '/pages/goods/addGoods' },
  { name: 'shop', text: '新品上架', link: '/pages/goods/newRelease?isDetail=false' }
]
const onClickBtn = (e) => {
  tab.navigateTo(floatBtns[e.index].link)
}

// 跳转详情
const handleToView = (productId) => {
  tab.navigateTo(`/pages/product/view?productId=${productId}&isSelf=${isSelf.value}&isCatalog=${curChildTab.value === '6'}`)
}

// 商品统计数据
const statisticData1 = ref([
  { name: '商品数量', value: 0, unit: '个' },
  { name: '直供商品', value: 0, unit: '个' },
  { name: '订单数量', value: 0, unit: '单' }
])
const statisticData2 = ref([
  { name: '商品数量', value: 0, unit: '个' },
  { name: '订单数量', value: 0, unit: '单' }
])
const getProductStaByHome = () => {
  try {
    productApi.getProductStaByHome({
      zhid: currentTenantId,
      gsid: currentDeptId,
      yhlx: userType.value
    }).then(res => {
      if (res.code === 0 && res.data) {
        if (userType.value === '2') {
          if (res.data.sptjxx[0]) {
            statisticData2.value[0].value = formatValue(res.data.sptjxx[0].val01)
            statisticData2.value[0].unit = formatUnit(res.data.sptjxx[0].val01, '个')
          }
          if (res.data.ddtjxx[0]) {
            statisticData2.value[1].value = formatValue(res.data.ddtjxx[0].val02)
            statisticData2.value[1].unit = formatUnit(res.data.ddtjxx[0].val02, '单')
          }
        } else {
          if (res.data.sptjxx[0]) {
            statisticData1.value[0].value = formatValue(res.data.sptjxx[0].val01)
            statisticData1.value[0].unit = formatUnit(res.data.sptjxx[0].val01, '个')
            statisticData1.value[1].value = formatValue(res.data.sptjxx[0].val04)
            statisticData1.value[1].unit = formatUnit(res.data.sptjxx[0].val04, '个')
          }
          if (res.data.ddtjxx[0]) {
            statisticData1.value[2].value = formatValue(res.data.ddtjxx[0].val02)
            statisticData1.value[2].unit = formatUnit(res.data.ddtjxx[0].val02, '单')
          }
        }
      } else {
        modal.msgError('获取统计数据失败！')
      }
    })
  } catch(err) {
    modal.msgError('获取统计数据失败！')
  }
}

// 商品标签页统计数据
const getProductStaByStatus = () => {
  try {
    productApi.getProductStaByStatus({
      supplierId: userType.value === '2' ? companyId : ''
    }).then(res => {
      if (res.code === 0 && res.data) {
        // 获取商品待审核、已驳回的角标数
        childTabs.value[1].badge = res.data.shzCount
        childTabs.value[2].badge = res.data.ybhCount
      } else {
        modal.msgError('获取统计数据失败！')
      }
    })
  } catch(err) {
    modal.msgError('获取统计数据失败！')
  }
}

// 商品列表
const queryParams = ref({})
const listData = ref([])
const moreState = ref(1)
const getProductList = () => {
  uni.stopPullDownRefresh()
  try {
    const apiUrl = isSelf.value ? 'getSelfProductList' : 'getSupplyProductList'
    queryParams.value.name = searchValue.value
    queryParams.value.tabType = curChildTab.value
    queryParams.value.supplierId = userType.value === '2' ? companyId : ''
    productApi[apiUrl](queryParams.value).then((res) => {      
      modal.closeLoading()
      if (res.code === 0) {
        const newData = res.data && res.data.list ? res.data.list : []
        if (queryParams.value.pageNo * queryParams.value.pageSize >= res.data.total) {
          moreState.value = 3
        } else {
          moreState.value = 1
        }
        if (queryParams.value.pageNo > 1) {
          listData.value = [...listData.value, ...newData]
        } else {
          listData.value = [...newData]
        }
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch(err) {
    modal.closeLoading()
  }
}

onShow(() => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 10
  }
  getProductStaByHome()
  getProductStaByStatus()
  getProductList()
})

// 下拉刷新
onPullDownRefresh(() => {
  queryParams.value.pageNo = 1
  getProductList()
})

// 上拉加载更多
onReachBottom(() => {
  if (moreState.value == 1) {
    modal.loading('加载中...')
    moreState.value = 2
    queryParams.value.pageNo++
    getProductList()
  }
})
</script>

<style lang="scss" scoped>
.page-product-list {
  .page-search {
    position: relative;
    width: 100%;
    margin: 30rpx 0 0;

    :deep(.fui-input__wrap) {
      padding: 20rpx 24rpx !important;
    }

    span {
      position: absolute;
      z-index: 10;
      right: 0;
      top: 0;
      font-size: 1.25rem;
      color: var(--fui-color-link);
      display: inline-block;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      font-size: 40rpx;
      color: var(--fui-color-link);
    }
  }

  ::v-deep .page-parent-tab {
    .fui-tabs__scrollbox {
      width: fit-content;
    }
    .fui-tabs__line-short {
      width: 64rpx !important;
    }
    .fui-tabs__item {
      padding-left: 5rpx;
      padding-right: 72rpx;
    }
  }

  ::v-deep .page-child-tab {
    position: relative;
    display: flex;
    margin-top: 10rpx;
    .fui-tabs__scrollbox {
      width: fit-content;
    }
    .fui-tabs__line-short {
      width: 64rpx !important;
    }
    .fui-tabs__item {
      flex-grow: 0;
      padding: 0;
      .fui-tabs__text {
        border-radius: 8rpx;
        background: #fff;
        margin-right: 35rpx;
        padding: 0 10rpx;
        line-height: 48rpx;
        white-space: nowrap;
        font-size: 24rpx !important;
        color: #333 !important;
        &.fui-tabs__selected-color {
          border: 2rpx solid #376dfe;
          background: #ecf4ff;
          font-weight: bold !important;
          color: #376dfe !important;
        }
      }
    }
    .ui-btn-primary_plain {
      position: absolute;
      top: 50%;
      right: 0;
      transform: translateY(-50%);
      .fui-button {
        background-color: #ecf4ff !important;
        font-weight: bold;
      }
    }
  }

  .product-list {
    padding-bottom: 15rpx;
    .product-item {
      width: 100%;
      background: #ffffff;
      border-radius: 16rpx;
      padding: 28rpx;
      box-sizing: border-box;
      margin-bottom: 30rpx;
      display: flex;

      .product-item-right {
        margin-left: 24rpx;
        width: calc(100% - 188rpx);
        .right-title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333333;
          margin-bottom: 16rpx;
        }
        .right-list {
          display: flex;
          flex-wrap: wrap;
          .right-text {
            width: 100%;
            font-size: 24rpx;
            font-weight: 400;
            color: #999999;
            display: flex;
            align-items: center;
            margin-bottom: 10rpx;

            image {
              padding-right: 10rpx;
            }

            span {
              color: #333333;
            }
            .right-number {
              font-weight: bold;
              color: #2c83fc;
              padding: 0 10rpx;
            }
          }
        }
      }
    }
  }
  .ui-float-btn {
    ::v-deep .fui-fab__btn-inner {
      font-size: 24rpx;
      color: #fff;
      letter-spacing: 4rpx;
    }
  }
}
</style>
